import React from 'react';
import { InfoTipsC, TableC, InputNumberC } from '../../../comps';
import { stringify } from 'qs';
import { message } from 'antd';
class RedirectTable extends React.Component {
  constructor() {
    super();
    this.state = {
      selectNeedHandleTable: [],
      dValue: null,
      layerColumns: [],
      expandedRowKeys: [],
      actualRate: '', //外部的表格
    };
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { setFieldsValue } = this.props.form;
    let expandArr = [];
    if (nextProps.temp != this.props.temp) {
      this.setState(
        {
          selectNeedHandleTable: this.handleData(nextProps.selectNeedHandleTable, expandArr),
          dValue: nextProps.dValue,
          layerColumns: nextProps.layerColumns,
          actualRate: nextProps.actualRate,
        },
        () => {
          setFieldsValue({
            plans: this.state.selectNeedHandleTable,
          });
          this.setState({
            expandedRowKeys: expandArr,
          });
        },
      );
    }
  }
  //初始化处理了下数据
  handleData = (datas, expandArr) => {
    let newArr = [];
    let parnetObj = [];
    //如果datas存在  如果是一个_则是第一层 如果是两个_则是第二层 然后根据第二层是否存在第二层的内容判断在谁下面
    if (datas?.length) {
      for (var i = 0; i < datas.length; i++) {
        expandArr.push(datas[i].key);
        if (datas[i].level.split('_').length == 2) {
          datas[i].edit = false;
          parnetObj = [];
          for (let j = 0; j < datas.length; j++) {
            if (datas[j].level.split('_').length == 3) {
              if (datas[j].level.indexOf(datas[i].level) == 0 && datas[j].level.split('_')[1] == datas[i].level.split('_')[1]) {
                datas[j].edit = false;
                parnetObj.push(datas[j]);
              }
            }
          }
          //此时是第一层
          newArr.push({
            ...datas[i],
            children: parnetObj,
          });
        }
      }
    }
    return newArr;
  };
  //树结构伸缩的展示
  onExpand = (expanded, record) => {
    const { expandedRowKeys } = this.state;
    let expandCloneArr = JSON.parse(JSON.stringify(expandedRowKeys));
    let newArr = null;
    if (!expanded) {
      newArr = expandCloneArr.filter((item) => item != record.key);
      this.setState({
        expandedRowKeys: newArr,
      });
    } else {
      expandCloneArr.push(record.key);
      this.setState({
        expandedRowKeys: expandCloneArr,
      });
    }
  };
  //取消
  cancel = (record) => {
    const { selectNeedHandleTable } = this.state;
    const { setFieldsValue } = this.props.form;
    let selectNeedHandleTableNew = JSON.parse(JSON.stringify(selectNeedHandleTable));
    let newArr = this.circleTableCancel(selectNeedHandleTableNew, record.key);
    this.setState(
      {
        selectNeedHandleTable: selectNeedHandleTableNew,
      },
      () => {
        setFieldsValue({
          plans: newArr,
        });
      },
    );
  };
  //递归取消事件
  circleTableCancel = (list, keys) => {
    for (let i = 0; i < list.length; i++) {
      if (list[i].key == keys) {
        list[i].edit = false;
      } else {
        if (list[i].children && list[i].children.length) {
          this.circleTableCancel(list[i].children, keys);
        }
      }
    }
    return list;
  };
  //保存
  save = (record) => {
    const { selectNeedHandleTable, actualRate } = this.state;
    const { setFieldsValue, getFieldsValue } = this.props.form;
    let selectNeedHandleTableNew = JSON.parse(JSON.stringify(selectNeedHandleTable));
    if (getFieldsValue()['inputNumber' + record.key] == null) {
      message.warning('现金余额为空不可以保存！');
      return;
    }
    let newArr = this.circeChangeTableSave(selectNeedHandleTableNew, record.key);
    this.setState(
      {
        selectNeedHandleTable: newArr,
      },
      () => {
        setFieldsValue({
          plans: newArr,
        });
        //保存的时候差值需要改变
        const tableListNes = JSON.parse(JSON.stringify(this.state.selectNeedHandleTable));
        let count = 0;
        tableListNes.forEach((item) => {
          count += Number(item.cashRate);
          if (item.children) {
            item.children.forEach((items) => {
              count += Number(items.cashRate);
            });
          }
        });
        let dvalues = count.toFixed(2) - actualRate;
        this.setState({
          dValue: dvalues,
        });
      },
    );
  };
  //递归保存
  circeChangeTableSave = (list, keys) => {
    const {
      form: { getFieldsValue },
    } = this.props;
    for (let i = 0; i < list.length; i++) {
      if (list[i].key == keys) {
        list[i].edit = false;
        list[i].cashRate = Number(getFieldsValue()['inputNumber' + keys]).toFixed(2);
      } else {
        if (list[i].children && list[i].children.length) {
          this.circeChangeTableSave(list[i].children, keys);
        }
      }
    }
    return list;
  };
  //递归改变数组中的额某个数据
  circeChangeTable = (list, keys) => {
    for (let i = 0; i < list.length; i++) {
      if (list[i].key == keys) {
        list[i].edit = true;
      } else {
        if (list[i].children && list[i].children.length) {
          this.circeChangeTable(list[i].children, keys);
        }
      }
    }
    return list;
  };
  //编辑
  editFn = (record) => {
    const { selectNeedHandleTable } = this.state;
    const { setFieldsValue } = this.props.form;
    let selectNeedHandleTableNew = JSON.parse(JSON.stringify(selectNeedHandleTable));
    let newArr = this.circeChangeTable(selectNeedHandleTableNew, record.key);
    this.setState(
      {
        selectNeedHandleTable: selectNeedHandleTableNew,
      },
      () => {
        setFieldsValue({
          plans: newArr,
        });
      },
    );
  };
  //处理列
  handleColumns = (columns) => {
    if (columns?.length) {
      columns.map((item) => {
        item.width = '25%';
        if (item.key == 'combName') {
          item.title = <span style={{ marginLeft: '23px' }}>组合名称</span>;
        } else if (item.key == 'cashRate') {
          item.type = 'money';
          item.render = (text, record) => {
            if (record?.edit) {
              return <InputNumberC title='' dataIndex={'inputNumber' + record?.key} form={this.props.form} initialValue={text} precision={2} />;
            } else {
              return this.changeRender(text);
            }
          };
        } else if (item.title == '操作') {
          item.render = (text, record) => {
            if (record?.edit) {
              return (
                <>
                  <a onClick={() => this.save(record)}>保存</a>
                  <a onClick={() => this.cancel(record)}>取消</a>
                </>
              );
            } else {
              return (
                <>
                  <a onClick={() => this.editFn(record)}>编辑</a>
                </>
              );
            }
          };
        }
      });
    }
  };
  //处理千分位
  changeRender = (text) => {
    const test = Number(text)
      .toFixed(2)
      .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    return test;
  };
  //消息框
  LeftContent = () => {
    const { dValue } = this.state;
    return (
      <div>
        <span>真实金额与汇总现金余额有{this.changeRender(dValue)}元的差值</span>
      </div>
    );
  };
  render() {
    const { layerColumns, selectNeedHandleTable, expandedRowKeys } = this.state;
    this.handleColumns(layerColumns);
    return (
      <div id='tableLayer_mult'>
        <InfoTipsC Left={this.LeftContent()} style={{ paddingLeft: '20px', width: '100%' }}></InfoTipsC>
        <div style={{ marginTop: '12px' }}>
          <TableC
            rowKey='key'
            expandedRowKeys={expandedRowKeys}
            onExpand={this.onExpand}
            dataSource={selectNeedHandleTable}
            columns={layerColumns}
            hidePage={true}
            // scroll={{y:600}}
          ></TableC>
        </div>
      </div>
    );
  }
}
export default RedirectTable;
